/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.wisdom.common.github.modules.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 接口调用执行器
 * @author Administrator
 *
 */
public class HttpClientService {

	private static HttpClient getClient() {
		HttpClient httpClient = new HttpClient();
		httpClient.getParams().setContentCharset("UTF-8");
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000); //通过网络与服务器建立连接的超时时间
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(300000); //Socket读数据的超时时间，即从服务器获取响应数据需要等待的时间
		return httpClient;
	}
	
	public static  JSONObject putResponseData(String url, JSONObject params){
		PutMethod httpPut= new PutMethod(url);
		HttpClient httpClient =getClient();
		JSONObject jsonObject = new JSONObject();
		String response ="";
		try {
			httpPut.setRequestHeader("Content-Type", "application/json; charset=utf-8");
			if(params!=null){
				Set<String> set = params.keySet();
				List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
				for(Iterator<String> iter = set.iterator(); iter.hasNext();) {
				   String key = (String)iter.next();
				   String value = params.get(key) == null ? null : params.get(key).toString();
				   if(value != null)
					   formparams.add(new NameValuePair(key, value));
				}
				httpPut.setQueryString(formparams.toArray(new NameValuePair[formparams.size()]));
			}
			int statusCode = httpClient.executeMethod(httpPut);
			if (statusCode != HttpStatus.SC_OK) {
				jsonObject = new JSONObject();
				jsonObject.put("msg", statusCode + "请求出错！");
				jsonObject.put("http_status", false);
				return jsonObject;
			}
			byte[] responseBody = httpPut.getResponseBody();// 读取为字节数组
			response = new String(responseBody);
			jsonObject = JSONObject.parseObject(response);
			if(jsonObject==null){
				jsonObject=new JSONObject();
				jsonObject.put("http_status", true);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject=new JSONObject();
			jsonObject.put("http_status", false);
		} finally {
	        if (null != httpPut)
	        	httpPut.releaseConnection();
	    }
		return jsonObject;
	}
	
	@SuppressWarnings("deprecation")
	public static JSONObject postResponseData(String url, JSONObject params){
		PostMethod httpPost = new PostMethod(url);
		HttpClient httpClient = getClient();
		JSONObject jsonObject = new JSONObject();
		String response ="";
		try {
			httpPost.addRequestHeader("Content-Type", "application/json; charset=utf-8");
			if(params!=null){
//				Set<String> set = params.keySet();
//				List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
//				for(Iterator<String> iter = set.iterator(); iter.hasNext();) {
//				   String key = (String)iter.next();
//				   String value = params.get(key) == null ? null : params.get(key).toString();
//				   if(value != null)
//					   formparams.add(new NameValuePair(key, value));
//				}
				httpPost.setRequestBody(params.toString());
//				httpPost.setRequestBody(formparams.toArray(new NameValuePair[formparams.size()]));
			}
			int statusCode = httpClient.executeMethod(httpPost);
			if (statusCode != HttpStatus.SC_OK) {
				jsonObject = new JSONObject();
				jsonObject.put("http_status", false);
				jsonObject.put("msg", statusCode + "请求出错！");
				return jsonObject;
			}
			byte[] responseBody = httpPost.getResponseBody();// 读取为字节数组
			response = new String(responseBody,"utf-8");
			
			try{
				jsonObject.put("data", JSONArray.parse(response));
			}catch(ClassCastException e){
				jsonObject.put("data", JSONObject.parse(response));
			}
			jsonObject.put("http_status", true);
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("http_status", false);
			jsonObject.put("msg", response);
		} finally {
	        if (null != httpPost)
	        	httpPost.releaseConnection();
	    }
		return jsonObject;
	}
	
	/**
	 * 直接调用ouath
	 * @param url
	 * @param params
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static JSONObject postOauthResponseData(String url, String params){
		PostMethod httpPost = new PostMethod(url);
		HttpClient httpClient = getClient();
		JSONObject jsonObject = new JSONObject();
		String response ="";
		try {
			httpPost.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
			httpPost.addRequestHeader("authorization","Basic cGlnOnBpZw==");
			httpPost.setRequestBody(params);

			int statusCode = httpClient.executeMethod(httpPost);
			if (statusCode != HttpStatus.SC_OK) {
				jsonObject = new JSONObject();
				jsonObject.put("http_status", false);
				jsonObject.put("msg", statusCode + "请求出错！");
				return jsonObject;
			}
			byte[] responseBody = httpPost.getResponseBody();// 读取为字节数组
			response = new String(responseBody,"utf-8");
			
			try{
				jsonObject.put("data", JSONArray.parse(response));
			}catch(ClassCastException e){
				jsonObject.put("data", JSONObject.parse(response));
			}
			jsonObject.put("http_status", true);
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("http_status", false);
			jsonObject.put("msg", response);
		} finally {
	        if (null != httpPost)
	        	httpPost.releaseConnection();
	    }
		return jsonObject;
	}
	
	public static JSONObject getResponseData(String url){
		GetMethod httpGet = new GetMethod(url);
		HttpClient httpClient = getClient();
		String response="";
		JSONObject jsonObject = new JSONObject();
		try {
			httpGet.setRequestHeader("Content-Type", "application/json; charset=utf-8");
			int statusCode = httpClient.executeMethod(httpGet);
			if (statusCode != HttpStatus.SC_OK) {
				jsonObject = new JSONObject();
				jsonObject.put("msg", statusCode + "请求出错！");
				jsonObject.put("http_status", false);
				return jsonObject;
			}
			byte[] responseBody = httpGet.getResponseBody();// 读取为字节数组
			response = new String(responseBody,"utf-8");
			try{
				jsonObject.put("data", JSONArray.parse(response));
			}catch(ClassCastException e){
				jsonObject.put("data", JSONObject.parse(response));
			}
			jsonObject.put("http_status", true);
		}catch (JSONException e) {
			jsonObject = new JSONObject();
			jsonObject.put("msg",response);
			jsonObject.put("http_status", true);
			return jsonObject;
		} catch (Exception e) {
			jsonObject=new JSONObject();
			jsonObject.put("http_status", false);
		} finally {
	        if (null != httpGet)
	        	httpGet.releaseConnection();
	    }
		return jsonObject;
	}
	public static void main(String[] args) {
//		String url = "http://upms.dev.m8cmp.com/user/roles/1";
//		String url = "http://gateway.dev.m8cmp.com/auth/oauth/token";
		String url = "http://m8cmp-flow-engine-m8cmp-v1-dev.m8cd.com/m8cmp-app/app/rest/form-models/checkForm";
		Integer randomStr =(int)((Math.random()*9+1)*10000);
		JSONObject params = new JSONObject();
		params.put("formList", "f2f569ca515143fb91b04e4c0915a896,f2f569ca515143fb91b04e4c0915a894");
		params.put("user_id", 1);
//		params.put("randomStr", randomStr+"_"+System.currentTimeMillis());
//		params.put("code", "");
//		params.put("grant_type", "password");
//		params.put("scope", "server");
//		
//		JSONObject jsonObject = ActivitiClientService.getResponseData(url);
		
//		String params ="{formList:\"f2f569ca515143fb91b04e4c0915a896,f2f569ca515143fb91b04e4c0915a894\",user_id\":1}";
		JSONObject jsonObject = HttpClientService.postResponseData(url, params);
		
		System.out.println(jsonObject);
//		String []str=jsonObject.get("response").toString().split("\n");
		
	}
}